package net.gianrishandy.jbase.connection;

import java.io.File;
import java.sql.DriverManager;

import net.gianrishandy.jbase.connection.interfaces.ConnectionType;

/**
 * @author Gian Rishandy
 *
 */
public class Connection implements ConnectionType{
	
	/**
	 * Active database connection
	 */
	public static java.sql.Connection databaseConnection = null;
	
	/**
	 * Connection type of database
	 */
	public static int connectionType = -1;
	
	/**
	 * TCP/IP of database
	 */
	public static String host = "";
	
	/**
	 * Database port
	 */
	public static String port = "";
	
	/**
	 * Database name
	 */
	public static String databaseName = "";
	
	/**
	 * User name to connect database
	 */
	public static String username = "";
	
	/**
	 * Password to connect database
	 */
	public static String password = "";
	
	/**
	 * File of database. Only for SQLite and Ms. Access
	 */
	public static File databaseFile = null;
	
	/**
	 * Connect to database, set connectionType, databaseName, username, password and databaseFile first!
	 * 
	 * @return true = success to connect database and false = failed to connect database
	 * @throws Exception
	 */
	public static boolean connectToDatabase() throws Exception{
		String url = "";
		switch(connectionType){
			case MySQL :
				Class.forName("com.mysql.jdbc.Driver");
				url = "jdbc:mysql://" + host + "/" + databaseName;
				break;
			case PostgreSQl : 
				Class.forName("org.postgresql.Driver");
				url = "jdbc:postgresql://" + host + "/" + databaseName;
				break;
			case SQLServer : 
				Class.forName("net.sourceforge.jtds.jdbc.Driver");
				url = "jdbc:jtds:sqlserver://" + host + "/" + databaseName;
				break;
			case SQLite :
				Class.forName("org.sqlite.JDBC");
				url = "jdbc:sqlite:" + databaseFile.getPath();
				break;
			case MsAccess : 
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + databaseFile.getPath();
				break;
			default: break;
		}
		
		if(!url.equalsIgnoreCase("")){
			databaseConnection = DriverManager.getConnection(url, username, password);
			return true;
		}
		
		return false;
	}
	
	/**
	 * Begin transaction if database support this method
	 */
	public static void beginTran(){
		try {
			databaseConnection.setAutoCommit(false);
		} catch (Exception e) {
			System.err.println(e);
		}
	}
	
	/**
	 * Commit if database support this method
	 */
	public static void commit(){
		try {
			databaseConnection.commit();
		} catch (Exception e) {
			System.err.println(e);
		}
	}
	
	/**
	 * Roll back if database support this method
	 */
	public static void rollback(){
		try {
			databaseConnection.rollback();
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}
